package vois

import (
	"bytes"
	"encoding/xml"
	"fmt"
)

// Parse <sayas-at>...<sayas-at> tags.
func processSayasAt(dec *xml.Decoder, e xml.StartElement) (VOISSayasAt, error) {
	var secopy xml.StartElement
	var cdcopy xml.CharData
	var ee xml.EndElement
	var token xml.Token
	var err error
	var vsa VOISSayasAt
	var attr xml.Attr
	var havesayas bool
	var cd xml.CharData
	var ok bool
	var bfr *bytes.Buffer
	havesayas = false
	secopy = e.Copy()
	for _, attr = range secopy.Attr {
		if attr.Name.Local == "sayas" {
			vsa.Sayas = attr.Value
			havesayas = true
			break
		}
	}
	if havesayas == false {
		return vsa, buildVOISError("<sayas-at> is missing the sayas attribute.")
	}
	token, err = dec.Token()
	switch token.(type) {
	case xml.CharData:
		cd, ok = token.(xml.CharData)
		cdcopy = cd.Copy()
		bfr = bytes.NewBuffer(cdcopy)
		vsa.Xpath = bfr.String()
		// get the end tag
		token, err = dec.Token()
		ee, ok = token.(xml.EndElement)
		if ok == false {
			return vsa, buildVOISError("token to end element error.")
		}
		if ee.Name.Local != "sayas-at" {
			return vsa, buildVOISError(fmt.Sprintf("unmatched </%s>", ee.Name.Local))
		} else {
			return vsa, err
		}
	default:
		return vsa, buildVOISError("<sayas-at> is missing the character data.")
	}
}

// Parse <sayas-text>...</sayas-text> tags.
func processSayasText(dec *xml.Decoder, e xml.StartElement) (VOISSayasText, error) {
	var secopy xml.StartElement
	var cdcopy xml.CharData
	var ee xml.EndElement
	var token xml.Token
	var err error
	var vst VOISSayasText
	var attr xml.Attr
	var havesayas bool
	var cd xml.CharData
	var ok bool
	var bfr *bytes.Buffer
	havesayas = false
	secopy = e.Copy()
	for _, attr = range secopy.Attr {
		if attr.Name.Local == "sayas" {
			vst.Sayas = attr.Value
			havesayas = true
			break
		}
	}
	if havesayas == false {
		return vst, buildVOISError("<sayas-text> is missing the sayas attribute.")
	}
	token, err = dec.Token()
	switch token.(type) {
	case xml.CharData:
		cd, ok = token.(xml.CharData)
		cdcopy = cd.Copy()
		bfr = bytes.NewBuffer(cdcopy)
		vst.Text = bfr.String()
		// get the end tag
		token, err = dec.Token()
		ee, ok = token.(xml.EndElement)
		if ok == false {
			return vst, buildVOISError("token to end element error.")
		}
		if ee.Name.Local != "sayas-text" {
			return vst, buildVOISError(fmt.Sprintf("unmatched </%s>", ee.Name.Local))
		} else {
			return vst, err
		}
	default:
		return vst, buildVOISError("<sayas-text> is missing the character data.")
	}
}
